﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DataGridFilter.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace DataGridFilter.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        private readonly List<Employee> _employees;

        [ObservableProperty]
        private ICollectionView _collectionView;

        [ObservableProperty]
        private string filterText;

        partial void OnFilterTextChanged(string value) => _collectionView.Refresh();

        [RelayCommand]
        private void AddEmployee()
        {
            _employees.Add(Employee.FakeOne());
            CollectionView.Refresh();
            //_collectionView.Refresh();//也行
        }

        public MainWindowViewModel(IEnumerable<Employee> employees)
        {
            _employees = new List<Employee>(employees);
            CollectionView = CollectionViewSource.GetDefaultView(_employees);
            CollectionView.Filter = NameFilter;
        }

        private bool NameFilter(object obj)
        {
            if (string.IsNullOrWhiteSpace(FilterText)) return true;
            var employee = obj as Employee;
            return employee!.FirstName.ToUpper().Contains(filterText.ToUpper()) 
                || employee!.LastName.ToUpper().Contains(filterText.ToUpper());
        }
    }//end of class
}
